<?php
class Database extends PDO {
    function __construct($dsn, $username="", $password="", $driver_options=array()) {
		parent::__construct($dsn,$username,$password, $driver_options);

		// Do I need this?
		$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array($this)));
	}

	public function exec($statement)
    {
        $statement = $this->_tablePrefixSuffix($statement);
        return parent::exec($statement);
    }

    public function prepare($statement, $driver_options = array())
    {
        $statement = $this->_tablePrefixSuffix($statement);
        return parent::prepare($statement, $driver_options);
    }

    public function query($statement)
    {
        $statement = $this->_tablePrefixSuffix($statement);
        $args      = func_get_args();

        if (count($args) > 1) {
            return call_user_func_array(array($this, 'parent::query'), $args);
        } else {
            return parent::query($statement);
        }
    }

	public function insert($table, $data) {
		$keys = array();
		$values = array();
		$binds = array();

		$i = 0;

		foreach($data as $k=>$v) {
			$keys[] = "`" . str_replace("`", "``", $k) . "`";
			$values[] = ":" . $i;
			$binds[":".$i] = $v;

			$i++;
		}

		$keys = implode(", ", $keys);
		$values = implode(", ", $values);

		$sql = "INSERT INTO {prefix}$table ($keys) VALUES($values)";

		$stmt = $this->prepare($sql);

		return $stmt->execute($binds);
	}

    protected function _tablePrefixSuffix($statement)
    {
        return str_replace("{prefix}", Config::$database_settings["prefix"], $statement);
    }
}

class DBStatement extends PDOStatement {
    public $dbh;
    protected function __construct($dbh) {
        $this->dbh = $dbh;
    }

	public function fetch($fetch_style = PDO::FETCH_ASSOC, $cursor_orientation = PDO::FETCH_ORI_NEXT,
			$cursor_offset = 0) {

		return parent::fetch($fetch_style, $cursor_orientation, $cursor_offset);
	}
}
?>
